import request, {pubUrl,pubHost} from "@/common/request.js";
//引入上面封装好的请求方法
const getPageList = (pageinfo) => {	
  return request({
    url: "/api/wms_online/getPageList",
	method: "POST",
    data: pageinfo,
  });
};
const addDbIncheckOrder = (data,userid,pass_status,flag='wg') => {//wg cp 外购入 、产品入
	if(pass_status==0){
		//质检
		return request({
		  url: "/api/wms_online/addDbIncheckOrder",
		  method: "POST",
		  data: {
				porders:data,
				uuid:uni.getStorageSync('uuid'),
				userid:userid,
				flag:flag
			},
		});
	}else{
		//移库
		return request({
		  url: "/api/wms_online/addDbYikuOrder",
		  method: "POST",
		  data: {
				porders:data,
				uuid:uni.getStorageSync('uuid'),
				userid:userid
			},
		});
	}
};
const toFh = (data,userid,order_type) => {//复核pda单据
	//复核pda单据
	return request({
	  url: "/api/wms_online/toFh",
	  method: "POST",
	  data: {
			porders:data,
			uuid:uni.getStorageSync('uuid'),
			userid:userid,
			order_type:order_type
		},
	});
};
const getAccount = (data) => {
  return request({
    url: "/api/Item/getAccount",
    data: data,
  });
};
const getSupplier = (data) => {
  return request({
    url: "/api/Item/getSupplier",
    data: data,
  });
};
const getConsumer = (data) => {
  return request({
    url: "/api/Item/getConsumer",
    data: data,
  });
};
const getStock = (data) => {
  return request({
    url: "/api/Item/getStock",
    data: data,
  });
};
const getDepartment = (data) => {
  return request({
    url: "/api/Item/getDepartment",
    data: data,
  });
};
const getCurrency = (data) => {
  return request({
    url: "/api/Item/getCurrency",
    data: data,
  });
};
const getMaterial = (data) => {
  return request({
    url: "/api/Item/getMaterial",
    data: data,
  });
};
const getUnit = (data) => {
  return request({
    url: "/api/Item/getUnit",
    data: data,
  });
};
const getSettle = (data) => {
  return request({
    url: "/api/Item/getSettle",
    data: data,
  });
};


const getlist = (page) => {
  return request({
    url: "/api/Instock/getlist",
    data: { page: page },
  });
};
const getdetails = (id) => {
  return request({
    url: "/api/Instock/getdetails",
    data: { id: id },
  });
};

const addpoorder = (data) => {
  return request({
    url: "/api/Poorder/addpoorder",
    method: "POST",
    data: data,
  });
};
//同步时判断本地单据状态，未同步，但服务器确存在（有可能网络原因，导致无法更新）
//20230127
const synPdaPcOrderStatus = (bills,allots,checks) => {
	let user = uni.getStorageSync('user')
	return request({
	  url: "/api/wms/synPdaPcOrderStatus",
	  method: "POST",
	  data:{
		  bills: JSON.stringify(bills),
		  allots: JSON.stringify(allots),
		  checks: JSON.stringify(checks),
		  uuid:uni.getStorageSync('uuid'),
		  userid:user.userid,
		  username:user.username
	  }
	});
};
//获取sql
const getPcSql = () => {
  return request({
    url: "/api/wms/getPcSql"
  });
};
//获取pc端最大单号
//20230127
const getTodayMaxCode = (cdate = '') => {
	return request({
	  url: "/api/wms/getTodayMaxCode",
	  data:{
		  uuid:uni.getStorageSync('uuid'),
		  cdate:cdate
	  }
	});
};
//批量回传出入库单
const addstockbills = (billentrys,allots,checks) => {
  //数组转json
  let user = uni.getStorageSync('user')
  
  return request({
    url: "/api/wms/addStockBills",
    method: "POST",
    data:{
		billentry: JSON.stringify(billentrys),
		allots: JSON.stringify(allots),
		checks: JSON.stringify(checks),
		uuid:uni.getStorageSync('uuid'),
		userid:user.userid,
		username:user.username,
		online:uni.getStorageSync('myconfig').online
	}
  });
};
//回传出入库单
const addstockbill = (bill,billentry,pdatype) => {
  //数组转json
  let user = uni.getStorageSync('user')
  return request({
    url: "/api/wms/addStockBill",
    method: "POST",
    data:{
		bill: JSON.stringify(bill),
		billentry: JSON.stringify(billentry),
		pdatype:pdatype,
		uuid:uni.getStorageSync('uuid'),
		userid:user.userid,
		username:user.username,
		online:uni.getStorageSync('myconfig').online
		}
  });
};
//回传盘点单
const addcheckinvbill = (bills) => {
  return request({
    url: "/api/item/addCheckInventoryBill",
    method: "POST",
    data:{checkbill: bills,uuid:uni.getStorageSync('uuid')}
  });
};
//获取同步时间
const getSyntime = () => {
  return request({
    url: "/../uploads/data/syn_datetime.json"
  });
};
//销售订单报表
const getseorderbywifi = (page,keyword) => {
  return request({
    url: "/api/item/getSeorderBywifi",
    data: { pageNumber: page,pageSize:20,keyword:keyword },
  });
};
//最新销售订单记录
const getlatestoneseorder = () => {
  return request({
    url: "/api/item/getLatestOneSeorder",
    data: {},
  });
};

const addseorder = (data) => {
  return request({
    url: "/api/Seorder/addseorder",
    method: "POST",
    data: data,
  });
};
const getseorder_list = (page) => {
  return request({
    url: "/api/Seorder/getseorder_list",
    data: { page: page },
  });
};
const getseorder_details = (id) => {
  return request({
    url: "/api/Seorder/getseorder_details",
    data: { id: id },
  });
};

const addseoutorder = (data) => {
  return request({
    url: "/api/Seoutorder/addseoutorder",
    method: "POST",
    data: data,
  });
};
const getseoutorder_list = (page) => {
  return request({
    url: "/api/Seoutorder/getseoutorder_list",
    data: { page: page },
  });
};
const getseoutorder_details = (id) => {
  return request({
    url: "/api/Seoutorder/getseoutorder_details",
    data: { id: id },
  });
};

const addsample = (data) => {
  return request({
    url: "/api/Sampleorder/addsample",
    method: "POST",
    data: data,
  });
};
const getsample_list = (page) => {
  return request({
    url: "/api/Sampleorder/getsample_list",
    data: { page: page },
  });
};
const getsample_details = (id) => {
  return request({
    url: "/api/Sampleorder/getsample_details",
    data: { id: id },
  });
};

const getreportlist = (page, type) => {
  return request({
    url: "/api/Inventoryreport/getreportlist",
    data: { page: page, type: type },
  });
};

//同步wms单据回pda
const synPdaorder = (order_type,status = 1) => {
  return request({
    url: "/api/wms/synPdaorder",
    method: "POST",
    data: {uuid:uni.getStorageSync('uuid'),status:status,order_type:order_type},
  });
};
//同步日志到服务器
const synActionLog = (data) => {
  return request({
    url: "/api/wms/synActionLog",
	method:"POST",
    data: { data: JSON.stringify(data) },
  });
};
//撤销同步状态
const unSyn = (FBillNo) => {
  return request({
    url: "/api/wms/unSyn",
    data: { order_code: FBillNo , uuid:uni.getStorageSync('uuid')},
  });
};

const getorderdateil = (id) => {
   return request({
    url: "/api/Instock/getorderdateil",
    data: { id: id },
  }); 
};
const getcodedateil = (code) => {
  /* return request({
    url: "/api/Common/getcodedateil",
    data: { code: code },
  }); */
  
};

const select = (page) => {
  return request({
    url: "/api/Poorder/select",
    data: { page: page },
  });
};

const synchJiDei = () => {
  return request({
    url: "/api/Poorder/synchJiDei",
  });
};

const synchinstock = (data) => {
  return request({
    url: "/api/Instock/synchinstock",
    method: "POST",
    data: data,
  });
};

//20230127
const getJsonUrl = (fname) => {
	return request({
	  url: "/api/wms/getjson",//Poorder
	  data:{filename:fname}
	});
};
const getJsonContent = (filename) => {
	return new Promise((resolve, reject) => {
		plus.io.resolveLocalFileSystemURL("_doc/json/"+filename+'.json', function( fileEntry ) {
			//console.log(fileEntry.fullPath)
			fileEntry.file(function(file) {
				 var fileReader = new plus.io.FileReader();
				 fileReader.readAsText(file, 'utf-8');
				 fileReader.onloadend = function(evt) {
					 resolve(evt.target.result);
				 }
			});
		},function(e){
			//console.log(e);
		});
	});
};

const toCopy = (filename,urlpath) => {//pubUrl
	let flag = false;
	
	plus.io.resolveLocalFileSystemURL("_doc/json/"+filename, function( oldentry ) {
		if(!oldentry.isFile){
			msg('复制失败,目标是目录');
			return ;
		}
		
		 oldentry.remove( function(){
			 console.log('删除本地成功');
			 flag = true;
		 }, function(){
			  console.log('删除本地失败');
		 });
	},function(e){
		console.log(e);
		flag = true;
	});
	
	const downloadTask = uni.downloadFile({
		url: pubHost+urlpath,
		success: (res) => {
			if (res.statusCode === 200) {
				console.log('下载成功');
			}
			//console.log(res.tempFilePath);
			plus.io.resolveLocalFileSystemURL(res.tempFilePath,function(entry){
				if(!entry.isFile){
					msg('同步失败,目标是目录');
					return ;
				}
				
			   plus.io.resolveLocalFileSystemURL("_doc",function(root){
				  entry.copyTo( root, 'json/'+filename, function( entry2 ){
					  console.log(filename+"拷贝成功");
					  let filename_arr = filename.split('.')
					  uni.$emit('downloadOK',filename_arr[0])
					  //console.log( entry2.fullPath)  
				  },function(e){
					   console.log(e)
					   plus.console.log("New Path: " + e.fullPath);
			           console.log("拷贝失败");
			       }); 
				});
			 });
			/* 
			//保存路径不能自己定义
			uni.saveFile({
				tempFilePath: res.tempFilePath,
				success: function(red) {
					//that.luj = red.savedFilePath
					console.log(red)
				}
			}); */
		}
	}); 
	
	
	downloadTask.onProgressUpdate((res) => {
		if(res.progress == 100){
			/* uni.showToast({
				icon:"none",
				title:'同步成功'
			}) */
			/* console.log('下载进度' + res.progress);
			console.log('已经下载的数据长度' + res.totalBytesWritten);
			console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite); */
		}
		//
	});
};

const getNeedArr = (array,size,keyword,listname) => {
	if(keyword!=''){
		if(listname=='inventory'){
			
			let inputSoArr1 = array.filter((ev) => {
					return ev.FName.indexOf(keyword) != -1;
			});
			let inputSoArr2 = array.filter((ev) => {
					return ev.FNumber.indexOf(keyword) != -1;
			});
			let inputSoArr3 = array.filter((ev) => {
					return ev.FBatchNo.indexOf(keyword) != -1;
			});
			
			//合并数组
			var newdata = inputSoArr1.concat(inputSoArr2,inputSoArr3);
		}
		
		if(listname=='storehouse'){
			let inputSoArr1 = array.filter((ev) => {
					return ev.FName.indexOf(keyword) != -1;
			});
			let inputSoArr2 = array.filter((ev) => {
					return ev.FNumber.indexOf(keyword) != -1;
			});
			//合并数组
			var newdata = inputSoArr1.concat(inputSoArr2);
		}
		array = newdata
	}
	//获取所需指定长度分割的数组;参数1为用于分割的总数组,参数2为分割数组后每个小数组的长度
      const length = array.length;
      //判断不是数组，或者size没有设置，size小于1，就返回空数组
      if (!length || !size || size < 1) {
        return [];
      }
      //核心部分
      let index = 0; //用来表示切割元素的范围start
      let resIndex = 0; //用来递增表示输出数组的下标

      //根据length和size算出输出数组的长度，并且创建它。
      let result = new Array(Math.ceil(length / size));
      //进行循环
      while (index < length) {
        //循环过程中设置result[0]和result[1]的值。该值根据array.slice切割得到。
        result[resIndex++] = array.slice(index, (index += size));
      }
      //输出新数组
      return result;
};

const timeToDate = (createtime,form = 'Y-m-d') => {
      var date = new Date(createtime * 1000);
      let Y = date.getFullYear() + '-';
      let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) + '-' : date.getMonth() + 1 + '-';
      let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
      let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
      let m = date.getMinutes() < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
      let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
      if(form == 'Y-m-d'){
		  return Y + M + D;
	  }
	  return Y + M + D + h + m + s;
};
const msg = (content,icon='none') => {
	uni.showToast({
		icon:icon,
		title:content.toString(),
		duration:2500
	})
};
//获取pc端，是否有pda单据未处理
const getPcBillStatus = (order_type_arr = []) => {
	let order_type_str = ''
	if(order_type_arr.length > 0){
		order_type_str = order_type_arr.join(',')
	}
	
	return new Promise((resolve, reject) => {
		request({
		  url: "/api/wms/getPcBillStatus",
		  method: "POST",
		  data: {order_type_str:order_type_str},
		}).then(res=>{
			  if(res.data.code == 0){
				 reject(res.data.msg)
			  }else{
				  resolve(true)
			  }
		}).catch(err=>{
			  reject(err)
		});
	})
};

	
module.exports = {
  synchinstock, //在线上传外购入库单单据
  synchJiDei, //同步金蝶采购单据
  select, //获取采购源单
  getcodedateil, //获取条形码结果
  getorderdateil, //获取选择采购订单详情
  getPageList, //在线版，获得翻页列表
  getAccount, // 获取科目列表
  getSupplier, // 获取供应商列表
  getConsumer, // 获取客户列表
  getStock, // 获取仓库列表
  getDepartment, // 获取部门列表
  getCurrency, // 获取币别列表
  getMaterial, // 获取物料列表
  getUnit, // 获取单位列表
  getSettle, // 获取结算方式列表
  addDbIncheckOrder, //新增质检放行调拨单
  getlist, //获取外购入库列表
  getdetails, //外购入库单详情
  addpoorder, //新增采购订单（更新）
  getPcSql, //获取PC配置sql详情
  addstockbill, //单个回传出入库单据
  addstockbills,//批量回传出入库单据
  addcheckinvbill,//回传盘点单
  getseorderbywifi, //获取即时销售订单列表，默认当天
  getlatestoneseorder, //获取最新订单记录
  addseorder, //新增销售订单（更新）
  getseorder_list, //获取销售订单列表
  getseorder_details, //获取销售订单详情
  addseoutorder, //新增销售订单（更新）
  getseoutorder_list, //获取销售订单列表
  getseoutorder_details, //获取销售订单详情
  addsample, //新增样品申请单（更新）
  toFh, //复核pda单据
  
  synPdaPcOrderStatus, //同步本地未同步状态的单据，保证和pc状态一致
  synPdaorder, //同步wms平台pda单据
  getTodayMaxCode, //获取PC最大单号更新本机
  synActionLog, //回传日志
  unSyn, //撤销同步
  getSyntime, // 获取同步时间
  
  getJsonUrl,//获取json文件远程名,通用，传个json名就可
  getJsonContent,//获取json文件，本地获取
  toCopy,
  getNeedArr,
  timeToDate,//时间戳转日期
  msg,//提示消息
  getPcBillStatus
};
